package org.dk.phonemq;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@RocketMQMessageListener(topic = "phone-topic",consumerGroup = "phone_message")
public class PhoneMessage implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(String s) {

    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        //MessageListenerConcurrently普通消息 MessageListenerOrderly 顺序消息
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                //获取消息
                MessageExt messageExt = list.get(0);
                //重试次数
                int reconsumeTimes = messageExt.getReconsumeTimes();
                System.out.println(reconsumeTimes);
                //消息id
                String msgId = messageExt.getMsgId();
                System.out.println("消息id"+msgId);
                try {
                    Object mq = redisTemplate.boundHashOps("mq").get(msgId);
                    if (mq == null){
                        //主题
                        String topic = messageExt.getTopic();
                        System.out.println(topic);
                        //消息内容
                        String phone = new String(messageExt.getBody());
                        System.out.println("消息内容"+phone);

                        //初始化clnt,使用单例方式
                       /* YunpianClient clnt = new YunpianClient("6b3ee03d0f730196184864e960e826db").init();
                        Random random = new Random();
                        String code = "";
                        for(int i = 0; i < 6; i++){
                            int a = random.nextInt(10);
                            code += a;
                        }
                        //发送短信API
                        Map<String, String> param = clnt.newParam(2);
                        param.put(YunpianClient.MOBILE, phone);
                        param.put(YunpianClient.TEXT, "【彭斌】亲爱的用户您好，您的验证码是"+code+"。有效期为30分钟，请尽快验证");
                        Result<SmsSingleSend> r = clnt.sms().single_send(param);
                        //获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
                        if(r.getCode() ==  0){
                            redisTemplate.opsForValue().set(phone,code,30, TimeUnit.MINUTES);
                        }*/
                        //阿里发短信
                        DefaultProfile str = DefaultProfile.getProfile("cn-beijing", "LTAI4GCbdwnjCGwQj9Z3tr3N", "27ih4pc1W1tqey9X4mmCy1JUotAX7L");
                        //连接
                        DefaultAcsClient defaultAcsClient = new DefaultAcsClient(str);
                        CommonRequest commonRequest = new CommonRequest();
                        commonRequest.setSysMethod(MethodType.POST);//请求方式
                        commonRequest.setSysDomain("dysmsapi.aliyuncs.com");
                        commonRequest.setSysVersion("2017-05-25");
                        commonRequest.setSysAction("SendSms");
                        //接受方的手机号
                        commonRequest.putQueryParameter("PhoneNumbers",phone);
                        //签名
                        commonRequest.putQueryParameter("SignName","东科创想");
                        //短信模板
                        commonRequest.putQueryParameter("TemplateCode","SMS_162522027");
                        //fasong
                        String s = RandomStringUtils.randomNumeric(6);
                        commonRequest.putQueryParameter("TemplateParam","{\"sms_code\":\""+s+"\"}");
                        redisTemplate.opsForValue().set(phone,s,30, TimeUnit.MINUTES);
                        CommonResponse commonResponse = defaultAcsClient.getCommonResponse(commonRequest);
                        System.out.println(commonResponse);
                        System.out.println("消费成功");
                        redisTemplate.boundHashOps("mq").put(msgId,"1");
                       // clnt.close();
                    }else{
                        System.out.println("重复消费");
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                }catch (Exception e){
                    //重试次数大于三次直接返回
                    if(reconsumeTimes >= 3){
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
    }
}
